package com.kuangjia.conferenceroomrental.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kuangjia.conferenceroomrental.entity.Reservation;
import com.kuangjia.conferenceroomrental.entity.Room;
import com.kuangjia.conferenceroomrental.mapper.ReservationMapper;
import com.kuangjia.conferenceroomrental.mapper.RoomMapper;
import com.kuangjia.conferenceroomrental.service.ReservationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

@RestController
@RequestMapping("/reservations")
public class ReservationController {
    
    private final ReservationService reservationService;
    
    @Autowired
    private ReservationMapper reservationMapper;
    
    @Autowired
    private RoomMapper roomMapper;
    
    @Autowired
    public ReservationController(ReservationService reservationService) {
        this.reservationService = reservationService;
    }
    
    @PostMapping
    public ResponseEntity<Object> createReservation(@RequestBody Reservation reservation) {
        try {
            System.out.println("\n===============================================");
            System.out.println("【DEBUG】接收到创建预约请求 - " + new Date());
            System.out.println("【预约数据】: " + reservation);
            System.out.println("【会议室ID】: " + reservation.getRoomId());
            
            // 获取会议室信息以便打印日志
            if (reservation.getRoomId() != null) {
                try {
                    Room room = roomMapper.selectById(reservation.getRoomId());
                    if (room != null) {
                        System.out.println("【会议室名称】: " + room.getName());
                        System.out.println("【会议室状态】: " + room.getStatus());
                    } else {
                        System.out.println("【错误】: 未找到ID为" + reservation.getRoomId() + "的会议室");
                    }
                } catch (Exception e) {
                    System.err.println("【错误】: 查询会议室信息失败: " + e.getMessage());
                }
            }
            
            System.out.println("【原始开始时间】: " + reservation.getStartTime());
            System.out.println("【原始结束时间】: " + reservation.getEndTime());
            System.out.println("【数据库格式开始时间】: " + (reservation.getStartTime() != null ? 
                reservation.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : "null"));
            System.out.println("【数据库格式结束时间】: " + (reservation.getEndTime() != null ? 
                reservation.getEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : "null"));
            System.out.println("【用途】: " + reservation.getPurpose());
            System.out.println("【参会人数】: " + reservation.getAttendees());
            
            if (reservation.getRoomId() == null) {
                System.err.println("【错误】: roomId为空");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("message", "会议室ID不能为空");
                errorResponse.put("success", false);
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            if (reservation.getUserId() == null) {
                System.err.println("【错误】: userId为空");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("message", "用户ID不能为空");
                errorResponse.put("success", false);
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 检查时间是否为空
            if (reservation.getStartTime() == null || reservation.getEndTime() == null) {
                System.err.println("【错误】: 开始时间或结束时间为空");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("message", "开始时间和结束时间不能为空");
                errorResponse.put("success", false);
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 检查开始时间是否早于结束时间
            if (reservation.getStartTime().isAfter(reservation.getEndTime()) ||
                reservation.getStartTime().isEqual(reservation.getEndTime())) {
                System.err.println("【错误】: 开始时间必须早于结束时间");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("message", "开始时间必须早于结束时间");
                errorResponse.put("success", false);
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 设置创建和更新时间
            LocalDateTime now = LocalDateTime.now();
            if (reservation.getCreatedAt() == null) {
                reservation.setCreatedAt(now);
            }
            if (reservation.getUpdatedAt() == null) {
                reservation.setUpdatedAt(now);
            }
            
            // 如果状态为空，设置为待审批
            if (reservation.getStatus() == null || reservation.getStatus().isEmpty()) {
                reservation.setStatus("PENDING");
            }
            
            // 打印即将进行的冲突检测信息
            System.out.println("\n【执行时间冲突检测】");
            System.out.println("【会议室ID】: " + reservation.getRoomId());
            System.out.println("【开始时间】: " + reservation.getStartTime());
            System.out.println("【结束时间】: " + reservation.getEndTime());
            System.out.println("【ISO格式开始时间】: " + 
                (reservation.getStartTime() != null ? 
                reservationService.formatToIsoDateTime(reservation.getStartTime()) : "null"));
            System.out.println("【ISO格式结束时间】: " + 
                (reservation.getEndTime() != null ? 
                reservationService.formatToIsoDateTime(reservation.getEndTime()) : "null"));
            
            // 查询该会议室在这个时间段内的所有预约
            System.out.println("\n【查询现有预约】:");
            try {
                List<Reservation> existingReservations = reservationMapper.selectList(
                    new LambdaQueryWrapper<Reservation>()
                        .eq(Reservation::getRoomId, reservation.getRoomId())
                        .in(Reservation::getStatus, Arrays.asList("PENDING", "APPROVED"))
                );
                
                System.out.println("【该会议室现有预约总数】: " + existingReservations.size());
                for (Reservation existing : existingReservations) {
                    System.out.println("  - 预约ID: " + existing.getId() + 
                                     ", 状态: " + existing.getStatus() + 
                                     ", 时间: " + existing.getStartTime() + " 至 " + existing.getEndTime());
                }
                
                // 手动检查每个预约是否有时间冲突
                System.out.println("\n【手动检查时间冲突】:");
                for (Reservation existing : existingReservations) {
                    boolean hasOverlap = !(existing.getEndTime().isBefore(reservation.getStartTime()) || 
                                         existing.getStartTime().isAfter(reservation.getEndTime()));
                    
                    System.out.println("  - 预约ID: " + existing.getId() + 
                                     ", 冲突: " + hasOverlap + 
                                     ", 开始时间: " + existing.getStartTime() + 
                                     ", 结束时间: " + existing.getEndTime());
                }
                
            } catch (Exception e) {
                System.err.println("【错误】: 查询现有预约失败: " + e.getMessage());
            }
            
            // 检查时间冲突，包括待审批的预约
            boolean hasTimeConflict = reservationService.hasTimeConflict(
                    reservation.getRoomId(), reservation.getStartTime(), reservation.getEndTime());
            
            System.out.println("\n【冲突检测结果】: " + (hasTimeConflict ? "存在冲突" : "无冲突"));
            
            if (hasTimeConflict) {
                System.err.println("【错误】: 发现时间冲突");
                List<Reservation> conflicts = reservationService.getConflictingReservations(
                        reservation.getRoomId(), reservation.getStartTime(), reservation.getEndTime());
                System.err.println("【冲突预约数量】: " + conflicts.size());
                
                for (Reservation conflict : conflicts) {
                    System.err.println("  - 冲突预约ID: " + conflict.getId() + 
                                     ", 状态: " + conflict.getStatus() + 
                                     ", 时间: " + conflict.getStartTime() + " 至 " + conflict.getEndTime());
                }
                
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("message", "该时间段已被预约或有待审批的预约，请选择其他时间");
                errorResponse.put("success", false);
                errorResponse.put("hasConflict", true);
                errorResponse.put("conflictingReservations", conflicts);
                return ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse);
            }
            
            System.out.println("\n【未检测到时间冲突】，准备创建预约");
            
            // 创建预约
            Reservation createdReservation = reservationService.createReservation(reservation);
            System.out.println("【预约创建成功】");
            System.out.println("【ID】: " + createdReservation.getId());
            System.out.println("【状态】: " + createdReservation.getStatus());
            System.out.println("===============================================\n");
            
            return ResponseEntity.status(HttpStatus.CREATED).body(createdReservation);
        } catch (Exception e) {
            System.err.println("\n【创建预约时发生错误】");
            System.err.println("【错误类型】: " + e.getClass().getName());
            System.err.println("【错误消息】: " + e.getMessage());
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("message", "创建预约失败: " + e.getMessage());
            errorResponse.put("success", false);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Reservation> getReservationById(@PathVariable Long id) {
        Reservation reservation = reservationService.getReservationById(id);
        if (reservation == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(reservation);
    }
    
    @GetMapping
    public ResponseEntity<List<Reservation>> getAllReservations() {
        List<Reservation> reservations = reservationService.getAllReservations();
        return ResponseEntity.ok(reservations);
    }
    
    @GetMapping("/page")
    public ResponseEntity<Map<String, Object>> getReservationsByPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<Reservation> page = new Page<>(current, size);
        IPage<Reservation> pageResult = reservationService.getReservationsByPage(page);
        
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("size", pageResult.getSize());
        result.put("current", pageResult.getCurrent());
        result.put("pages", pageResult.getPages());
        
        return ResponseEntity.ok(result);
    }
    
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Reservation>> getReservationsByUserId(@PathVariable Long userId) {
        List<Reservation> reservations = reservationService.getReservationsByUserId(userId);
        return ResponseEntity.ok(reservations);
    }
    
    @GetMapping("/user/{userId}/page")
    public ResponseEntity<Map<String, Object>> getReservationsByUserIdPage(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<Reservation> page = new Page<>(current, size);
        IPage<Reservation> pageResult = reservationService.getReservationsByUserIdPage(page, userId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("size", pageResult.getSize());
        result.put("current", pageResult.getCurrent());
        result.put("pages", pageResult.getPages());
        
        return ResponseEntity.ok(result);
    }
    
    @GetMapping("/room/{roomId}")
    public ResponseEntity<List<Reservation>> getReservationsByRoomId(@PathVariable Long roomId) {
        List<Reservation> reservations = reservationService.getReservationsByRoomId(roomId);
        return ResponseEntity.ok(reservations);
    }
    
    @GetMapping("/room/{roomId}/page")
    public ResponseEntity<Map<String, Object>> getReservationsByRoomIdPage(
            @PathVariable Long roomId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<Reservation> page = new Page<>(current, size);
        IPage<Reservation> pageResult = reservationService.getReservationsByRoomIdPage(page, roomId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("size", pageResult.getSize());
        result.put("current", pageResult.getCurrent());
        result.put("pages", pageResult.getPages());
        
        return ResponseEntity.ok(result);
    }
    
    @GetMapping("/status/{status}")
    public ResponseEntity<List<Reservation>> getReservationsByStatus(@PathVariable String status) {
        List<Reservation> reservations = reservationService.getReservationsByStatus(status);
        return ResponseEntity.ok(reservations);
    }
    
    @GetMapping("/status/{status}/page")
    public ResponseEntity<Map<String, Object>> getReservationsByStatusPage(
            @PathVariable String status,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<Reservation> page = new Page<>(current, size);
        IPage<Reservation> pageResult = reservationService.getReservationsByStatusPage(page, status);
        
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("size", pageResult.getSize());
        result.put("current", pageResult.getCurrent());
        result.put("pages", pageResult.getPages());
        
        return ResponseEntity.ok(result);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<Reservation> updateReservation(@PathVariable Long id, @RequestBody Reservation reservation) {
        Reservation existingReservation = reservationService.getReservationById(id);
        if (existingReservation == null) {
            return ResponseEntity.notFound().build();
        }
        
        reservation.setId(id);
        Reservation updatedReservation = reservationService.updateReservation(reservation);
        return ResponseEntity.ok(updatedReservation);
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteReservation(@PathVariable Long id) {
        Reservation existingReservation = reservationService.getReservationById(id);
        if (existingReservation == null) {
            return ResponseEntity.notFound().build();
        }
        
        reservationService.deleteReservation(id);
        return ResponseEntity.noContent().build();
    }
    
    @PostMapping("/check-conflict")
    public ResponseEntity<?> checkTimeConflict(@RequestBody Map<String, Object> request) {
        try {
            System.out.println("==== 接收到检查时间冲突请求 ====");
            System.out.println("请求数据: " + request);
            
            // 解析请求参数
            Long roomId = null;
            String roomName = null;
            LocalDateTime startTime = null;
            LocalDateTime endTime = null;
            String rawStartTime = null;
            String rawEndTime = null;
            
            try {
                // 解析会议室ID
                if (request.containsKey("roomId")) {
                    if (request.get("roomId") instanceof Number) {
                        roomId = ((Number) request.get("roomId")).longValue();
                    } else if (request.get("roomId") instanceof String) {
                        roomId = Long.parseLong((String) request.get("roomId"));
                    }
                }
                
                // 解析会议室名称
                if (request.containsKey("roomName") && request.get("roomName") instanceof String) {
                    roomName = (String) request.get("roomName");
                }
                
                // 解析时间
                if (request.containsKey("startTime") && request.get("startTime") instanceof String) {
                    rawStartTime = (String) request.get("startTime");
                    // 使用ISO_DATE_TIME解析器处理UTC时间
                    startTime = LocalDateTime.parse(rawStartTime, DateTimeFormatter.ISO_DATE_TIME);
                    System.out.println("解析后的开始时间: " + startTime + " (原始: " + rawStartTime + ")");
                    // 打印数据库查询格式
                    System.out.println("数据库查询格式开始时间: " + startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
                
                if (request.containsKey("endTime") && request.get("endTime") instanceof String) {
                    rawEndTime = (String) request.get("endTime");
                    // 使用ISO_DATE_TIME解析器处理UTC时间
                    endTime = LocalDateTime.parse(rawEndTime, DateTimeFormatter.ISO_DATE_TIME);
                    System.out.println("解析后的结束时间: " + endTime + " (原始: " + rawEndTime + ")");
                    // 打印数据库查询格式
                    System.out.println("数据库查询格式结束时间: " + endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
            } catch (Exception e) {
                System.err.println("解析请求参数失败: " + e.getMessage());
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("error", "解析请求参数失败: " + e.getMessage());
                errorResult.put("success", false);
                return ResponseEntity.badRequest().body(errorResult);
            }
            
            // 验证参数
            if ((roomId == null && roomName == null) || startTime == null || endTime == null) {
                String errorMsg = "缺少必要参数: roomId=" + roomId + ", roomName=" + roomName + 
                                ", startTime=" + startTime + ", endTime=" + endTime;
                System.err.println(errorMsg);
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("error", errorMsg);
                errorResult.put("success", false);
                return ResponseEntity.badRequest().body(errorResult);
            }
            
            // 检查时间冲突
            boolean hasConflict = false;
            List<Reservation> conflictingReservations = new ArrayList<>();
            
            if (roomId != null) {
                // 优先使用会议室ID查询冲突
                if (rawStartTime != null && rawEndTime != null) {
                    // 使用ISO时间格式方法
                    hasConflict = reservationService.hasTimeConflictIso(roomId, rawStartTime, rawEndTime);
                    if (hasConflict) {
                        conflictingReservations = reservationService.getConflictingReservationsIso(roomId, rawStartTime, rawEndTime);
                    }
                } else {
                    // 使用原有方法
                    hasConflict = reservationService.hasTimeConflict(roomId, startTime, endTime);
                    if (hasConflict) {
                        conflictingReservations = reservationService.getConflictingReservations(roomId, startTime, endTime);
                    }
                }
            } else if (roomName != null) {
                // 使用会议室名称查询冲突
                hasConflict = reservationService.hasTimeConflictByRoomName(roomName, startTime, endTime);
                if (hasConflict) {
                    conflictingReservations = reservationService.getConflictingReservationsByRoomName(roomName, startTime, endTime);
                }
            }
            
            if (hasConflict) {
                System.out.println("发现冲突预约数量: " + conflictingReservations.size());
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("hasConflict", hasConflict);
            result.put("conflictingReservations", conflictingReservations);
            result.put("success", true);
            result.put("message", hasConflict ? "该时间段已被预约，请选择其他时间" : "没有时间冲突");
            
            System.out.println("==== 返回检查结果 ====");
            System.out.println("结果: " + result);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            System.err.println("==== 检查时间冲突时发生错误 ====");
            System.err.println("错误消息: " + e.getMessage());
            e.printStackTrace();
            
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("error", e.getMessage());
            errorResult.put("success", false);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
    }
    
    @PutMapping("/{id}/approve")
    public ResponseEntity<Reservation> approveReservation(@PathVariable Long id) {
        Reservation existingReservation = reservationService.getReservationById(id);
        if (existingReservation == null) {
            return ResponseEntity.notFound().build();
        }
        
        Reservation approvedReservation = reservationService.approveReservation(id);
        return ResponseEntity.ok(approvedReservation);
    }
    
    @PutMapping("/{id}/reject")
    public ResponseEntity<Reservation> rejectReservation(@PathVariable Long id) {
        Reservation existingReservation = reservationService.getReservationById(id);
        if (existingReservation == null) {
            return ResponseEntity.notFound().build();
        }
        
        Reservation rejectedReservation = reservationService.rejectReservation(id);
        return ResponseEntity.ok(rejectedReservation);
    }
    
    @PutMapping("/{id}/cancel")
    public ResponseEntity<Reservation> cancelReservation(@PathVariable Long id) {
        Reservation existingReservation = reservationService.getReservationById(id);
        if (existingReservation == null) {
            return ResponseEntity.notFound().build();
        }
        
        Reservation cancelledReservation = reservationService.cancelReservation(id);
        return ResponseEntity.ok(cancelledReservation);
    }
    
    // 添加一个专用于测试的接口方法
    @GetMapping("/debug-conflict")
    public ResponseEntity<?> debugTimeConflict(
            @RequestParam Long roomId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        
        System.out.println("\n===============================================");
        System.out.println("【调试冲突检测】 - " + new Date());
        System.out.println("【会议室ID】: " + roomId);
        System.out.println("【开始时间】: " + startTime);
        System.out.println("【结束时间】: " + endTime);
        
        try {
            // 1. 先获取会议室详情
            Room room = roomMapper.selectById(roomId);
            if (room != null) {
                System.out.println("【会议室名称】: " + room.getName());
                System.out.println("【会议室状态】: " + room.getStatus());
            } else {
                System.err.println("【错误】: 未找到指定会议室");
                return ResponseEntity.badRequest().body("未找到指定会议室");
            }
            
            // 2. 获取该会议室所有预约
            List<Reservation> allReservations = reservationMapper.selectList(
                new LambdaQueryWrapper<Reservation>()
                    .eq(Reservation::getRoomId, roomId)
                    .in(Reservation::getStatus, Arrays.asList("PENDING", "APPROVED"))
            );
            
            // 3. 手动检查每个预约的时间冲突
            System.out.println("\n【手动检查所有预约】");
            System.out.println("该会议室现有预约总数: " + allReservations.size());
            
            List<Reservation> manualConflicts = new ArrayList<>();
            
            for (Reservation existing : allReservations) {
                boolean conflicts = !(existing.getEndTime().isEqual(startTime) || existing.getEndTime().isBefore(startTime) || 
                                    existing.getStartTime().isEqual(endTime) || existing.getStartTime().isAfter(endTime));
                                    
                System.out.println("预约ID: " + existing.getId() + 
                                 ", 状态: " + existing.getStatus() + 
                                 ", 开始: " + existing.getStartTime() + 
                                 ", 结束: " + existing.getEndTime() + 
                                 ", 冲突: " + conflicts);
                
                if (conflicts) {
                    manualConflicts.add(existing);
                }
            }
            
            // 4. 使用服务方法检查冲突
            boolean hasConflictService = reservationService.hasTimeConflict(roomId, startTime, endTime);
            List<Reservation> serviceConflicts = reservationService.getConflictingReservations(roomId, startTime, endTime);
            
            // 5. 使用直接SQL检查
            int directSqlCount = reservationMapper.checkTimeConflict(roomId, startTime, endTime);
            List<Reservation> directSqlConflicts = reservationMapper.getConflictingReservations(roomId, startTime, endTime);
            
            // 6. 使用精确范围检查
            List<Reservation> exactRangeConflicts = reservationService.findReservationsInTimeRange(roomId, startTime, endTime);
            
            // 汇总信息
            Map<String, Object> results = new HashMap<>();
            results.put("startTime", startTime);
            results.put("endTime", endTime);
            results.put("roomId", roomId);
            results.put("roomName", room.getName());
            results.put("allReservationsCount", allReservations.size());
            results.put("manualConflicts", manualConflicts);
            results.put("manualConflictsCount", manualConflicts.size());
            results.put("serviceHasConflict", hasConflictService);
            results.put("serviceConflicts", serviceConflicts);
            results.put("serviceConflictsCount", serviceConflicts.size());
            results.put("directSqlHasConflict", directSqlCount > 0);
            results.put("directSqlConflictsCount", directSqlCount);
            results.put("directSqlConflicts", directSqlConflicts);
            results.put("exactRangeConflicts", exactRangeConflicts);
            results.put("exactRangeConflictsCount", exactRangeConflicts.size());
            
            System.out.println("\n【冲突检测结果汇总】");
            System.out.println("手动检查冲突数: " + manualConflicts.size());
            System.out.println("服务方法检查结果: " + hasConflictService + ", 冲突数: " + serviceConflicts.size());
            System.out.println("SQL直接查询冲突数: " + directSqlCount);
            System.out.println("精确范围查询冲突数: " + exactRangeConflicts.size());
            System.out.println("===============================================\n");
            
            return ResponseEntity.ok(results);
        } catch (Exception e) {
            System.err.println("【调试过程发生错误】: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("调试过程发生错误: " + e.getMessage());
        }
    }
} 